<template>
  <modal
    ref="testModal"
    :visible="userEditVisiable"
    title="修改用户"
    cancelText="取消按钮"
    okText="保存"
    @cancelHandler="onClose"
    @okHandler="handleSubmit"
  >
    <template slot="content">
      <a-form :form="form"> 
        <a-form-item label="用户名" v-bind="formItemLayout">
          <a-input readOnly v-decorator="['username']" />
        </a-form-item>
        <a-form-item label="角色" v-bind="formItemLayout">
          <a-select
            mode="multiple"
            style="width: 100%"
            v-decorator="['roleId', { rules: [{ required: true, message: '请选择角色' }] }]"
          >
            <a-select-option v-for="r in roleData" :key="r.roleId.toString()">{{ r.roleName }}</a-select-option>
          </a-select>
        </a-form-item> 
        <a-form-item label="手机号码" v-bind="formItemLayout">
          <a-input
            v-decorator="[
              'mobile',
              {
                rules: [
                  { required: false, message: '请输入正确的联系电话', pattern: /^1[3456789]\d{9}$/ },
                  { validator: this.handlePhoneCheck }
                ],
                validateTrigger: ['change', 'blur']
              }
            ]"
          />
        </a-form-item> 
        <a-form-item label="邮箱" v-bind="formItemLayout">
          <a-input
            v-decorator="[
              'email',
              {
                rules: [
                  { required: false, message: '请输入正确的邮箱', pattern: /[\w]+(\.[\w]+)*@[\w]+(\.[\w])+/ },
                  { validator: this.handlePhoneCheck }
                ],
                validateTrigger: ['change', 'blur']
              }
            ]"
          />
        </a-form-item>
        <a-form-item label="性别" v-bind="formItemLayout">
          <!--<a-input readOnly v-decorator="['ssex', { rules: [{ required: false, message: '性别不能为空' }] }]" />-->
          <a-select
            style="width: 100%"
            disabled
            v-decorator="['ssex', { rules: [{ required: false, message: '性别不能为空' }] }]"
          >
            <a-select-option key=1 value=1>男</a-select-option>
            <a-select-option key=2 value=2>女</a-select-option>
            <a-select-option key=3 value=3>保密</a-select-option>
          </a-select>
        </a-form-item> 
        <a-form-item label="状态" v-bind="formItemLayout">
          <a-select
            style="width: 100%"
            v-decorator="['stat', { rules: [{ required: true, message: '请选择状态' }] }]"
          >
            <a-select-option key=0 value=0>有效</a-select-option>
            <a-select-option key=1 value=1>锁定</a-select-option>
            <a-select-option key=2 value=2>禁用</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </template>
  </modal>
</template>
<script>
import modal from '~/tool/modal';
import { mapState, mapMutations } from 'vuex';

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 }
};
export default {
  name: 'UserEdit',
  components: { modal },
  props: {
    userEditVisiable: {
      default: false
    }
  },
  data() {
    return {
      formItemLayout,
      form: this.$form.createForm(this),
      deptTreeData: [],
      roleData: [],
      userDept: [],
      userId: '',
      loading: false
    };
  },
  computed: {
    ...mapState({
      currentUser: state => state.account.user
    })
  },
  methods: {
    ...mapMutations({
      setUser: 'account/setUser'
    }),
    handlePhoneCheck(rule, value, callback) {
      callback();
    },
    onClose() {
      this.loading = false;
      this.form.resetFields();
      this.$emit('close');
    },
    setFormValues({ ...user }) {
      this.userId = user.userId;
      let fields = ['username', 'email', 'stat', 'ssex', 'mobile'];
      Object.keys(user).forEach(key => {
        if (fields.indexOf(key) !== -1) {
          this.form.getFieldDecorator(key);
          let obj = {};
          obj[key] = user[key] == null?user[key]: ''+user[key];
          this.form.setFieldsValue(obj);
        }
      });
      if (user.roleId) {
        this.form.getFieldDecorator('roleId');
        let roleArr = user.roleId.split(',');
        this.form.setFieldsValue({ roleId: roleArr });
      } 
    },
    handleSubmit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.loading = true;
          let user = this.form.getFieldsValue();
          user.roleId = user.roleId.join(',');
          user.userId = this.userId; 
          this.$put('user', {
            ...user
          })
            .then(r => {
              this.loading = false;
              this.$emit('success');
              // 如果修改用户就是当前登录用户的话，更新其state
              if (user.username === this.currentUser.username) {
                this.$get(`user/${user.username}`).then(r => {
                  this.setUser(r.data);
                });
              }
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    }
  },
  watch: {
    userEditVisiable() {
      if (this.userEditVisiable) {
        this.$get('role').then(r => {
          this.roleData = r.data.data.rows;
        });
      }
    }
  }
};
</script>
